package com.hjsmallfly.syllabus.repository.mock_lesson.local

import com.hjsmallfly.syllabus.bean.SemesterData
import com.hjsmallfly.syllabus.ext.from_ui
import com.hjsmallfly.syllabus.repository.mock_lesson.MockLessonDataSource
import com.hjsmallfly.syllabus.room.record.MockLesson
import com.tencent.mmkv.MMKV
import rx.Observable

class MockLessonLocalDataSource : MockLessonDataSource {

    private val kv = MMKV.defaultMMKV()

    override fun queryNextSemester(): Observable<SemesterData> {
        return Observable.create<SemesterData> {
            it.onStart()
            val nextSemester = kv.decodeParcelable(EXTRA_NEXT_SEMESTER, SemesterData::class.java)
            if (nextSemester != null) {
                it.onNext(nextSemester)
                it.onCompleted()
            } else {
                it.onError(Throwable("Semester is empty."))
            }
        }.from_ui()
    }

    override fun saveNextSemester(nextSemester: SemesterData) {
        kv.encode(EXTRA_NEXT_SEMESTER, nextSemester)
    }

    override fun queryMockLesson(uid: Long, semester: SemesterData): Observable<MockLesson> {
        return Observable.create<MockLesson> {
            it.onStart()
            val mockLesson = kv.decodeParcelable(getMockLessonKey(uid, semester), MockLesson::class.java)
            if (mockLesson != null) {
                it.onNext(mockLesson)
                it.onCompleted()
            } else {
                it.onError(Throwable("MockLesson of this semester is empty."))
            }
        }.from_ui()
    }

    override fun saveMockLesson(uid: Long, mockLesson: MockLesson) {
        kv.encode(getMockLessonKey(uid, mockLesson.semester), mockLesson)
    }

    companion object {
        private const val EXTRA_NEXT_SEMESTER = "NextSemester"

        private fun getMockLessonKey(uid: Long, semester: SemesterData): String {
            return "MOCK_LESSON_${uid}_${semester.year}_${semester.semester}"
        }
    }
}